<?php

/**
 *    卖家的订单结算管理控制器
 *
 *    @author   yanghj 2015-01-07
 *    @usage    none
 */
class My_clearingApp extends StoreadminbaseApp
{
    var $_user_id;
    var $_order_clearing_mod;
    var $_clearing_start_time;//订单结算开始时间
    var $_clearing_ned_time;//订单结算结束时间
    var $_max_valid_time;//适合结算订单的时间(订单结算开始时间减去7天)
    var $_month_time;//每个月的一号时间
    var $_month_date;//当前的月份

    /* 构造函数 */

    function __construct()
    {
        $this->My_clearingApp();
    }

    function My_clearingApp()
    {
        parent::__construct();

        $this->_user_id = intval($this->visitor->get('user_id'));
        $this->_order_clearing_mod = & m('orderclearing');
        $this->_clearing_start_time = strtotime(date("Y-m").'-10');
        $this->_clearing_ned_time = strtotime(date("Y-m").'-16');
        $this->_max_valid_time = $this->_clearing_start_time - 3600*24*7;
        $this->_month_time  = strtotime(date("Y-m").'-01');
        $this->_month_date = date("Y年m月");
    }

    function index()
    {
        $clearing_status = isset($_GET['clearing_status']) ? intval($_GET['clearing_status']) : 1;
        $is_export = isset($_GET['export']) ? true : false;
       // $is_tclearing_date = time() > $this->_clearing_start_time && time() < $this->_clearing_ned_time ? true : false;//判断是否在结算期
        $is_tclearing_date = time() > $this->_clearing_start_time ? true : false;//判断是否在结算期
        /* 获取订单列表 */
        $data = $this->_get_orders_clearing($clearing_status,$is_export);
        if(!$data['total'] && $clearing_status !=2){
            $clearing_status = 2;
            $data = $this->_get_orders_clearing($clearing_status,$is_export);
        }
        $table_title = $clearing_status ==1 ? $this->_month_date.'期可结算订单' : $this->_month_date.'期已确认可结算订单';
        $orders = $data['orders'];
        $page = $data['page'];
        $total = $data['total'];

        /* 导出数据 */
        if($is_export && $data['total'])
        {
            $this->_out_put_excel($orders,$total,$table_title);
        }

        $this->_curlocal(LANG::get('seller_center'), 'index.php?app=seller', LANG::get('my_clearing'), 'index.php?app=my_clearing',LANG::get('seller_clearing'));

        /* 当前用户中心菜单 */
        $this->_curitem('seller_clearing');
        $this->_config_seo('title', Lang::get('seller_center') . ' - ' . Lang::get('my_clearing'));
        /* 显示订单列表 */
        $this->assign('page_info', $page);          //将分页信息传递给视图，用于形成分页条
        $this->assign('orders', $orders);
        $this->assign('total', $total);
        $this->assign('clearing_status', $clearing_status);
        $this->assign('is_tclearing_date', $is_tclearing_date);
        $this->display('my_clearing.index.html');
    }

    function record()
    {
        /* 获取订单列表 */
        $is_export = isset($_GET['export']) ? true : false;
        $data = $this->_get_orders_clearing(3);
        $orders = $data['orders'];
        $page = $data['page'];
        $total = $data['total'];

        /* 导出数据 */
        if($is_export && $data['total'])
        {
            $table_title = $data['already_date'][$data['date_month']].'已结算订单';
            $this->_out_put_excel($orders,$total,$table_title);
        }

        $this->_curlocal(LANG::get('seller_center'), 'index.php?app=seller', LANG::get('my_clearing'), 'index.php?app=my_clearing',LANG::get('seller_clearing_record'));

        /* 当前用户中心菜单 */
        $this->_curitem('seller_clearing_record');
        $this->_config_seo('title', Lang::get('seller_center') . ' - ' . Lang::get('my_clearing'));
        /* 显示订单列表 */
        $this->assign('page_info', $page);          //将分页信息传递给视图，用于形成分页条
        $this->assign('orders', $orders);
        $this->assign('total', $total);
        $this->assign('date_month', $data['date_month']);
        $this->assign('already_date', $data['already_date']);
        $this->display('my_clearing.record.html');
    }

    /**
     *    确认可结算订单状态
     *
     */
    function confirm()
    {

        $conditions = "clearing_status = 1 AND seller_id = {$this->_user_id} ";
        $this->_order_clearing_mod->edit($conditions, array('clearing_status'=>'2','affirm_time'=>time()));
        if ($this->_order_clearing_mod->has_error())
        {
            $this->show_warning('确认可结算订单失败!');
            return;
        }

        $this->show_message('操作成功!','已确认可结算订单','index.php?app=my_clearing&clearing_status=2');
        return;
    }

    /**
     *    获取往期已结算的数据日期,返回最后六期的数据
     *
     */
    function _get_already_date()
    {

        $arr = array();
        $sql ="SELECT finish_time FROM ".DB_PREFIX."order_clearing  WHERE clearing_status = 3 AND seller_id = {$this->_user_id} AND FROM_UNIXTIME(finish_time,'%Y-%m-%d H:i:s') between date_sub(now(),interval 8 month) AND now() GROUP BY FROM_UNIXTIME(finish_time,'%Y-%m') ORDER BY finish_time DESC ";
        $data = $this->_order_clearing_mod->getAll($sql);
        if($data)
        {
            foreach($data as $key => $val)
            {
                if($key > 6)
                {
                    break;
                }
                $arr[date('Y-m',$val['finish_time'])] = date('Y年m月',$val['finish_time']).'期';
            }
        }
        return $arr;

    }

    /**
     *    获取订单列表
     *
     *    @author    Garbin
     *    @return    void
     */
    function _get_orders_clearing($clearing_status = 1, $is_excel = false)
    {

        $arr = array();
        $data = array();
        $page = $this->_get_page(10);
        $report_order_mod = & m('reportorder');
        $report_rec_mod = & m('reportrec');
        $conditions = "order_c.clearing_status = {$clearing_status} AND order_p.seller_id = {$this->_user_id} ";
        if($clearing_status == 3)
        {
            $date_month = html_script($_GET['date_month']);
            $already_date = $this->_get_already_date();
            if(!$already_date)
            {
                return $arr ;
            }
            if(empty($date_month))
            {
                $date_month = key($already_date);
            }
            if(!array_key_exists($date_month,$already_date))
            {
                return $arr ;
            }
            $arr['date_month'] = $date_month;
            $arr['already_date'] = $already_date;
            $conditions .= "AND FROM_UNIXTIME(finish_time,'%Y-%m') = '{$date_month}'";
        }
       /* $conditions .= $this->_get_query_conditions(array(
            array(//按下单时间搜索,起始时间
                'field' => 'order_p.pay_time',
                'name' => 'add_time_from',
                'equal' => '>=',
                'handler' => 'gmstr2time',
            ),
            array(//按下单时间搜索,结束时间
                'field' => 'order_p.pay_time',
                'name' => 'add_time_to',
                'equal' => '<=',
                'handler' => 'gmstr2time_end',
            ),
            array(//按订单号
                'field' => 'order_p.order_sn',
                'name' => 'order_sn',
                'equal' => 'LIKE',
                'handler' => 'html_script',
            ),
        ));*/

        $limit = $is_excel ? '' : $page['limit'];

        /* 查找订单 */
        $orders = $report_order_mod->find(array(
            'conditions' => $conditions,
            'fields' => 'this.order_id,this.pay_time,this.order_sn,this.seller_id,this.discount,this.goods_amount,this.shipping_fee,this.order_amount,this.other_fee',
            'count' => true,
            'join' => 'has_orderclearing',
            'limit' => $limit,
            'order' => 'order_p.pay_time DESC',
        ));
        if($orders)
        {
            foreach($orders as $key => $val)
            {
                $orders_ids[] = $val['order_id'];
            }
            $page['item_count'] = $report_order_mod->getCount();
            $this->_format_page($page);


            $sql_rec = "SELECT order_g.order_id,order_g.rec_id,order_g.buyer_name,order_g.buyer_city,order_g.goods_name,order_g.goods_quantity,order_g.goods_price,order_g.goods_amount,order_g.base_price,order_g.service_fee_form, coalesce(order_r.returns_amount,0) as returns_amount,coalesce(order_r.quantity,0) as returns_quantity,coalesce(order_r.goods_amount,0) as returns_goods_amount,coalesce(order_r.buyer_shipping_fee,0) as buyer_shipping_fee FROM ".DB_PREFIX."report_rec order_g
            left join ".DB_PREFIX."report_returns order_r on order_g.rec_id = order_r.rec_id
            WHERE order_g.order_id " . db_create_in($orders_ids);

            $temp = $report_order_mod->getAll($sql_rec);
            if($temp)
            {
                foreach($temp as $key => $val)
                {
                    $goods_data[$val['order_id']][$val['rec_id']] = $val;
                }
            }


            foreach ($orders as $order_id => $order)
            {
                $returns_amount = 0.00;
                $service_fee = 0.00;
                $service_fee_scale = 0.00;
                $buyer_shipping_fee = 0.00;
                foreach ($goods_data[$order_id] as $key=>$goods)
                {
                    $goods['last_quantity'] = $goods['goods_quantity'] - $goods['returns_quantity'];
                    if($goods['service_fee_form'] == 1){
                        $goods['service_fee'] = $goods['last_quantity'] > 0 ? ($goods['goods_price'] - $goods['base_price']) * $goods['last_quantity'] : 0.00;
                        $goods['service_fee_unit_scale'] = '';
                        $goods['service_fee_scale'] = '';
                        $service_fee +=$goods['service_fee'];
                    }
                    if($goods['service_fee_form'] == 2){
                        $goods['service_fee_unit_scale'] = sprintf("%.2f%%",$goods['base_price']/1*100);
                        $goods['service_fee_scale']  = ($goods['goods_amount'] - $goods['returns_goods_amount']) * $goods['base_price'];
                        $goods['service_fee'] = '';
                        $goods['base_price'] = '';
                        $service_fee_scale +=$goods['service_fee_scale'];
                    }

                    $returns_amount += $goods['returns_amount'];
                    $buyer_shipping_fee += $goods['buyer_shipping_fee'];
                }

                $orders[$order_id]['buyer_shipping_fee'] = sprintf("%.2f",$buyer_shipping_fee);//卖家承担买家退货运费
                $orders[$order_id]['deal_amount'] = sprintf("%.2f",$orders[$order_id]['goods_amount'] + $orders[$order_id]['shipping_fee']);//订单交易金额
                $orders[$order_id]['last_store_amount'] = sprintf("%.2f",$orders[$order_id]['goods_amount'] + $orders[$order_id]['shipping_fee'] - $returns_amount);
                $orders[$order_id]['service_fee_sum'] = sprintf("%.2f",$service_fee+$service_fee_scale);//服务费用合计
                $orders[$order_id]['store_account_amount'] = sprintf("%.2f",$orders[$order_id]['last_store_amount'] - $orders[$order_id]['service_fee_sum']-$orders[$order_id]['other_fee']-$orders[$order_id]['buyer_shipping_fee']);//商户结算金额
                $orders[$order_id]['goods_count'] = count($goods_data[$order_id]);//商品个数
                $orders[$order_id]['goods'] = $goods_data[$order_id];//关联的商品

            }

            $sql_total = "SELECT COUNT(order_p.order_id) as order_sn,SUM(order_p.shipping_fee) as shipping_fee ,SUM(goods_quantity) as goods_quantity,SUM(order_p.other_fee) as other_fee,SUM(coalesce(r.returns_amount,0)) as returns_amount,SUM(order_p.goods_amount+order_p.shipping_fee) as deal_amount,SUM(coalesce(r.service_amount,0)) as service_fee,SUM(coalesce(r.service_fee_scale,0)) as service_fee_scale,SUM(coalesce(r.buyer_shipping_fee,0)) as buyer_shipping_fee  FROM ".DB_PREFIX."report_order order_p
        left join (
        SELECT order_g.order_id,SUM(order_g.goods_quantity) as goods_quantity,SUM(COALESCE (r.quantity, 0)) as returns_quantity,SUM(coalesce(r.returns_amount,0)) returns_amount,SUM(coalesce(r.buyer_shipping_fee,0)) buyer_shipping_fee,
    SUM(CASE WHEN order_g.service_fee_form=1 THEN ((order_g.goods_price - order_g.base_price) * (order_g.goods_quantity - COALESCE (r.quantity, 0))) ELSE 0 END) service_amount,
    SUM(CASE WHEN  order_g.service_fee_form=2  THEN ((order_g.goods_amount - COALESCE (r.goods_amount, 0)) * order_g.base_price) ELSE 0 END ) service_fee_scale
     FROM ".DB_PREFIX."report_rec order_g left join ".DB_PREFIX."report_returns r on order_g.rec_id = r.rec_id group by order_g.order_id) r on order_p.order_id = r.order_id
     left join ".DB_PREFIX."order_clearing order_c on order_c.order_id = order_p.order_id
    where {$conditions}";

            $total = $report_order_mod->getRow($sql_total);
            $total['pay_time'] = '合计';
            $total['service_fee_sum'] = sprintf("%.2f",$total['service_fee'] + $total['service_fee_scale']);
            $total['store_account_amount'] = sprintf("%.2f",$total['deal_amount'] - $total['returns_amount'] - $total['service_fee_sum'] - $total['other_fee']-$total['buyer_shipping_fee']);

        }

        $arr['page'] = $page;
        $arr['orders'] = $orders;
        $arr['total'] = $total;

        return $arr ;
    }

    function _out_put_excel($data,$total,$table_title)
    {


        $index = 1;
        foreach ($data as $order_id => $order)
        {
            sort($order['goods']);
            foreach ($order['goods'] as $key => $goods)
            {
                $rs[$index-1] = $goods;
                $rs[$index-1]['pay_time'] = date('Y-m-d',$order['pay_time']);
                $rs[$index-1]['order_sn'] = $order['order_sn'];
                $rs[$index-1]['shipping_fee'] = $order['shipping_fee'];
                $rs[$index-1]['order_amount'] = $order['order_amount'];
                $rs[$index-1]['deal_amount'] = $order['deal_amount'];
                $rs[$index-1]['other_fee'] = $order['other_fee'];
                $rs[$index-1]['service_fee_sum'] = $order['service_fee_sum'];
                $rs[$index-1]['store_account_amount'] = $order['store_account_amount'];
                if($key == 0 && $order['goods_count']>1)
                {
                    $rs[$index-1]['rowspan'] = $order['goods_count']-1;
                }

                $index++;
            }
        }

        $rs[] = $total;
        $heads = $this->_get_excel_heads();
        require(ROOT_PATH."/includes/PHPExcel/export_excel.php");
        createExcel($table_title, $heads, $rs);
        exit;
    }

    function _get_excel_heads()
    {
        return array(
            'pay_time' => array('name' => "交易时间"),
            'order_sn' => array('name' => "网上订单号"),
            'buyer_name' => array('name' => "买方"),
            'buyer_city' => array('name' => "买方所在城市"),
            'goods_name' => array('name' => "商品名称"),
            'goods_quantity' => array('name' => "商品数量"),
            'goods_price' => array('name' => "商品单价"),
            'returns_amount' => array('name' => "退货金额"),
            'shipping_fee' => array('name' => "物流费用", 'rowspan' => true),
            'deal_amount' => array('name' => "订单交易金额", 'rowspan' => true),
            'service_fee_sum' => array('name' => "服务费金额", 'rowspan' => true),
            'other_fee' => array('name' => "其他费用", 'rowspan' => true),
            'store_account_amount' => array('name' => "商家结算金额", 'rowspan' => true),

        );
    }


}

?>
